﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Threading;
using System.Windows;
using System.Windows.Media;
using EnvDTE80;
using EnvDTE;

namespace pklib {
	public delegate void NoArgsDelegate();

	public class DelayedCall {
		public DelayedCall(EventHandler objEvent) : this(objEvent, 50) { }
		public DelayedCall(EventHandler objEvent, int Interval) {
			DispatcherTimer objTimer = new DispatcherTimer(DispatcherPriority.Render, Dispatcher.CurrentDispatcher);

			objTimer.Interval = new TimeSpan(Interval * 10000);
			objTimer.IsEnabled = true;
			objTimer.Tick += objEvent;
			objTimer.Tick += (EventHandler)delegate(object sender, EventArgs e) {
				objTimer.IsEnabled = false;
			};
		}
	}

	public class Utils {
		public static void ClearDebugOutput() {
			EnvDTE80.DTE2 ide = (EnvDTE80.DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.9.0");
			ide.ExecuteCommand("Edit.ClearOutputWindow", "");
			System.Runtime.InteropServices.Marshal.ReleaseComObject(ide);
		}
	}

	public class Utility {
		static public childItem FindVisualChild<childItem>(DependencyObject obj)
				where childItem : DependencyObject {
			for ( int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++ ) {
				DependencyObject child = VisualTreeHelper.GetChild(obj, i);
				if ( child != null && child is childItem )
					return (childItem)child;
				else {
					childItem childOfChild = FindVisualChild<childItem>(child);
					if ( childOfChild != null )
						return childOfChild;
				}
			}
			return null;
		}
	}

	public class XOM {
		static public DependencyObject Up(DependencyObject Start, Type Search) {
			return XOM.Up(Start, Search, 1);
		}
		static public DependencyObject Up(DependencyObject Start, Type Search, int Count) {
			DependencyObject Object = Start;
			while ( (Object = VisualTreeHelper.GetParent(Object)) != null ) {
				if ( Object.GetType() == Search ) {
					Count--;
					if ( Count == 0 )
						return Object;
				}
			}
			return Object;
		}
		static public DependencyObject Down(DependencyObject Start, Type Search) {
			return XOM.Down(Start, Search, 1);
		}
		static public DependencyObject Down(DependencyObject Start, Type Search, int Count) {
			DependencyObject Object = Start;
			// Search immediate decendants
			for ( int j=0; j < VisualTreeHelper.GetChildrenCount(Start); j++ ) {
				DependencyObject dob = VisualTreeHelper.GetChild(Start, j);
				if ( dob.GetType() == Search ) {
					Count--;
					if ( Count == 0 )
						return dob;
					return XOM.Down(dob, Search, Count);
				}
			}
			// Search further decendants
			for ( int j=0; j < VisualTreeHelper.GetChildrenCount(Start); j++ ) {
				DependencyObject dob = XOM.Down(VisualTreeHelper.GetChild(Start, j), Search, Count);
				if ( dob != null )
					return dob;
			}
			return null;
		}
	}
}